package com.wowo.aop.transaction;

import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class App3 {

    public static void main(String[] args) {
        //设置所生成的代理类文件的目录
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,"D:\\cglib1");
        TransactionApsect transactionApsect = new TransactionApsect();
        MethodInterceptor m = new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                System.out.println(proxy.getSignature().toString()+" , "+proxy.getSuperName());
                transactionApsect.start();
                Object result = null;
                try {
                    result = proxy.invokeSuper(obj, args);
                    transactionApsect.commit();
                }catch (Exception e){
                    transactionApsect.rollback();
                }
                return result;
            }
        };
        //
        Enhancer enhancer = new Enhancer();
        // 设置其父类
        enhancer.setSuperclass(StudentServiceImpl.class);

        // 设置方法的处理
        enhancer.setCallback(m);
        //创建代理类对象
        StudentServiceImpl studentServiceImpl = (StudentServiceImpl) enhancer.create();
        studentServiceImpl.save();
        studentServiceImpl.update();
    }
}
